package com.djsearch.ui;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.json.JSONException;

import com.djsearch.R;
import com.djsearch.controller.AccessTokenKeeper;
import com.djsearch.controller.AsyncHandler;
import com.djsearch.controller.IRequest;
import com.djsearch.controller.IResponse;
import com.djsearch.controller.JSONReq;
import com.djsearch.controller.JSONResp;
import com.tencent.weibo.api.TAPI;
import com.tencent.weibo.constants.OAuthConstants;
import com.tencent.weibo.oauthv2.OAuthV2;
import com.weibo.sdk.android.Oauth2AccessToken;
import com.weibo.sdk.android.Weibo;
import com.weibo.sdk.android.WeiboAuthListener;
import com.weibo.sdk.android.WeiboDialogError;
import com.weibo.sdk.android.WeiboException;
import com.weibo.sdk.android.WeiboParameters;
import com.weibo.sdk.android.api.StatusesAPI;
import com.weibo.sdk.android.net.RequestListener;
import com.weibo.sdk.android.sso.SsoHandler;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Toast;

/**
 * 设置页面
 * 
 * @author yinxing
 * 
 */
public class SetActivity extends BaseActivity implements OnClickListener {

	/** 我的收藏 */
	RelativeLayout myFavorite;
	/** 个人信息 */
	RelativeLayout personalInformation;
	/** 我的订单 */
	RelativeLayout myOrder;
	/** 帮助 */
	RelativeLayout help;

	private Context mContext;
	private Button backBtn;
	private RelativeLayout helpLayout, myOrderLayout, myInfoLayout,myDingDanLayout;
	private CheckBox bindMobileCheck, bindIntroCheck;
	private AlertDialog.Builder inputPhoneNumDialog;
	private LayoutInflater layoutInflater;

	CheckBox sina;
	CheckBox tencent;
	public static Oauth2AccessToken accessToken;
	SsoHandler mSsoHandler;
	private Weibo mWeibo;
	private static final String CONSUMER_KEY = "1423547747";// 替换为开发者的appkey，例如"1646212860";
	private static final String REDIRECT_URL = "http://www.dianjinshou.cn";
	public static OAuthV2 oAuth;
	/**
	 * tx
	 */
	public static final String REDIRECTURI = "http://www.dianjinshou.cn";
	public static final String CLIENTID = "801340347";
	public static final String CLIENTSECRET = "1130fbac25f04642b506bcd9e518ed49";
	public String txToken;
	public static TAPI tAPI = new TAPI(OAuthConstants.OAUTH_VERSION_2_A);
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		mContext = this;
		layoutInflater = (LayoutInflater) this
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		getWindow().requestFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(
				WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
		setContentView(R.layout.set_layout);
		initView();
		initOnClick();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.my_favorite:

			break;
		case R.id.personal_information:
			startActivity(SetActivity.this, MyInfoActivity.class, 0);
			break;
		case R.id.my_order:

			break;
		case R.id.help:
			startActivity(SetActivity.this, HelpActivity.class, 0);
			break;
		default:
			break;
		}
	}

	@Override
	void initHandler() {

		
	}

	@Override
	void initView() {
		// TODO Auto-generated method stub
		myFavorite = (RelativeLayout) findViewById(R.id.my_favorite);
		personalInformation = (RelativeLayout) findViewById(R.id.personal_information);
		myOrder = (RelativeLayout) findViewById(R.id.my_order);
		help = (RelativeLayout) findViewById(R.id.help);
		backBtn = (Button) findViewById(R.id.btnBack);
		helpLayout = (RelativeLayout) findViewById(R.id.help);
		myOrderLayout = (RelativeLayout) findViewById(R.id.my_order);
		myInfoLayout = (RelativeLayout) findViewById(R.id.personal_information);
		bindMobileCheck = (CheckBox) findViewById(R.id.ismobile);
		if (preferences.getString("isBind", "no").equals("yes")) {
			bindMobileCheck.setButtonDrawable(R.drawable.checkbox_selected);
		}
		bindIntroCheck = (CheckBox) findViewById(R.id.istuijian);
		sina = (CheckBox) findViewById(R.id.issina);
		if (preferences.getString("isSinaBind", "no").equals("yes")) {
			sina.setButtonDrawable(R.drawable.checkbox_selected);
		}
		tencent = (CheckBox) findViewById(R.id.istencent);
		SetActivity.accessToken = AccessTokenKeeper.readAccessToken(this);
		mWeibo = Weibo.getInstance(CONSUMER_KEY, REDIRECT_URL);
		oAuth = new OAuthV2(REDIRECTURI);
		oAuth.setClientId(CLIENTID);
		oAuth.setClientSecret(CLIENTSECRET);
	}

	@Override
	void initOnClick() {
		// TODO Auto-generated method stub
		backBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startActivity(mContext, MainActivity.class, 2);
			}
		});
		helpLayout.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startActivity(mContext, HelpActivity.class, 0);
			}
		});
		myFavorite.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (isLogin()) {
					startActivity(mContext, MyCollectActivity.class, 0);
				} else {
					Toast.makeText(mContext, "你未登录，不能查看收藏", 5000).show();
				}
			}
		});
		myOrderLayout.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startActivity(mContext, SureOrderActivity.class, 0);
			}
		});
		myInfoLayout.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startActivity(mContext, MyInfoActivity.class, 0);
			}
		});
		bindMobileCheck
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						// TODO Auto-generated method stub
						if (isChecked) {

							// TODO Auto-generated method stub
							RelativeLayout layout = (RelativeLayout) layoutInflater
									.inflate(
											R.layout.input_phone_number_layout,
											null);
							if (inputPhoneNumDialog == null) {
								inputPhoneNumDialog = new Builder(
										SetActivity.this);
							}
							final EditText editText = (EditText) layout
									.findViewById(R.id.phoneNumEdit);
							inputPhoneNumDialog.setView(layout);
							inputPhoneNumDialog.setPositiveButton("确定",
									new DialogInterface.OnClickListener() {
										@Override
										public void onClick(
												DialogInterface arg0, int arg1) {
											if (editText.getText().toString()
													.equals("")) {
												startAnimation(editText);
											} else {
												bindPhoneNumber(editText);
											}
										}

									});
							inputPhoneNumDialog.setNegativeButton("取消",
									new DialogInterface.OnClickListener() {
										@Override
										public void onClick(
												DialogInterface arg0, int arg1) {
											bindMobileCheck.setChecked(false);
											arg0.dismiss();
										}
									});
							inputPhoneNumDialog.create();
							inputPhoneNumDialog.show();

						}
					}

				});
		sina.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				// TODO Auto-generated method stub
				if (!isBindSina()) {
					sinaAuthorize();
				} else {
					giveUpSinaAccessToken();
					sina.setButtonDrawable(R.drawable.checkbox_normal);
					Toast.makeText(mContext, "你已取消绑定", 5000).show();
				}
			}
		});
		tencent.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				// TODO Auto-generated method stub
				Intent intent;
				intent = new Intent(SetActivity.this,
						OAuthV2AuthorizeWebView.class);// 创建Intent，使用WebView让用户授权
				intent.putExtra("oauth", oAuth);
				startActivityForResult(intent, 2);
			}
		});
	}

	/**
	 * 绑定手机号
	 */
	private void bindPhoneNumber(EditText editText) {
		// TODO Auto-generated method stub
		IRequest request = new JSONReq("telephone");
		/**
		 * data={"userId":"8765","telephone":"1234567890"}
		 */
		showDialog("正在绑定手机号...");
		request.putParam("userId", preferences.getString("userId", ""));
		request.putParam("telephone", editText.getText().toString());
		HTTP.post(request, new AsyncHandler() {
			@Override
			public void onSuccess(JSONResp response) {
				// TODO Auto-generated method stub
				int result = response.result();
				if (IResponse.Success == result) {
					missDialog();
					getDataToResolve(response);
				} else if (IResponse.Fail == result) {
					// 登陆失败
					bindMobileCheck.setChecked(false);
					Toast.makeText(mContext, "绑定失败", 5000).show();
				}

				missDialog();
			}

			@Override
			public void onFailure(Throwable e, String response) {
				// TODO Auto-generated method stub
				super.onFailure(e, response);
				missDialog();
				bindMobileCheck.setChecked(false);
				Toast.makeText(mContext, "绑定失败", 5000).show();
			}

		});
	}

	public void sinaAuthorize() {

		mSsoHandler = new SsoHandler(SetActivity.this, mWeibo);
		mSsoHandler.authorize(new AuthDialogListener());
	}

	
	
	
	
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		oAuth = new OAuthV2(REDIRECTURI);
		oAuth.setClientId(CLIENTID);
		oAuth.setClientSecret(CLIENTSECRET);
	}

	/**
	 * 点击返回键
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		startActivity(mContext, MainActivity.class, 2);
		return super.onKeyDown(keyCode, event);
	}

	@Override
	void getDataToResolve(JSONResp response) {
		// TODO Auto-generated method stub
		try {
			String message = response.getString("message");
			bindMobileCheck.setChecked(true);
			bindMobileCheck.setButtonDrawable(R.drawable.checkbox_selected);
			SharedPreferences.Editor editor = preferences.edit();
			editor.putString("isBind", "yes").commit();
			Toast.makeText(mContext, message, 5000).show();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	class AuthDialogListener implements WeiboAuthListener {

		@Override
		public void onComplete(Bundle values) {
			String token = values.getString("access_token");
			String expires_in = values.getString("expires_in");
			SetActivity.accessToken = new Oauth2AccessToken(token, expires_in);
			saveSinaAccessToken(token, expires_in);
			if (SetActivity.accessToken.isSessionValid()) {
				long date = accessToken.getExpiresTime();
				/**
				 * 存储token
				 */
//				ctx.GetAdapter().UpdateSinaToken(token.UserId, token, date);
				try {
					Class sso = Class
							.forName("com.weibo.sdk.android.api.WeiboAPI");// 如果支持weiboapi的话，显示api功能演示入口按钮
				} catch (Exception e) {
					// e.printStackTrace();
				}
				AccessTokenKeeper
						.keepAccessToken(SetActivity.this, accessToken);
				Toast.makeText(SetActivity.this, "绑定成功", Toast.LENGTH_SHORT)
						.show();
				sina.setChecked(true);
				sina.setButtonDrawable(R.drawable.checkbox_selected);
				
				
//				StatusesAPI apiii = new StatusesAPI(SetActivity.accessToken);
////				apiii.update(content, lat, lon, listener)
//				apiii.update("我刚刚关注了@起点读书端，客户端下载", "", "", new RequestListener() {
//					@Override
//					public void onIOException(IOException arg0) {
//						// TODO Auto-generated method stub
//					}
//
//					@Override
//					public void onError(WeiboException arg0) {
//						// TODO Auto-generated method stub
//					}
//
//					@Override
//					public void onComplete(String arg0) {
//						// TODO Auto-generated method stub
//
////						Toast.makeText(mContext, "分享成功", 5000).show();
//					}
//				} );
				
				
				
			}
		}

		@Override
		public void onError(WeiboDialogError e) {
			Toast.makeText(getApplicationContext(),
					"Auth error : " + e.getMessage(), Toast.LENGTH_LONG).show();
		}

		@Override
		public void onCancel() {
			Toast.makeText(getApplicationContext(), "Auth cancel",
					Toast.LENGTH_LONG).show();
		}

		@Override
		public void onWeiboException(WeiboException e) {
			Toast.makeText(getApplicationContext(),
					"Auth exception : " + e.getMessage(), Toast.LENGTH_LONG)
					.show();
		}

	}

	
	/**
	 * 取消绑定
	 * @param token
	 * @param expires_in
	 */
    private void giveUpSinaAccessToken() {
		
		SharedPreferences.Editor editor = preferences.edit();
		editor.putString("sinaToken", "").commit();
		editor.putString("sinaexpiresIn", "").commit();
		editor.putString("isSinaBind", "no").commit();
	}
	

	private void saveSinaAccessToken(String token,String expires_in) {
		
		SharedPreferences.Editor editor = preferences.edit();
		editor.putString("sinaToken", token).commit();
		editor.putString("sinaexpiresIn", expires_in).commit();
		editor.putString("isSinaBind", "yes").commit();
	}
	
	
	/**
	 * 保存腾讯token
	 * @param txToken
	 */
    private void saveTecentAccessToken(String txToken,String clientId,String clientSecret,String redirectUri) {
		SharedPreferences.Editor editor = preferences.edit();
		editor.putString("tecentToken", txToken).commit();
		editor.putString("clientId", clientId).commit();
		editor.putString("clientSecret", clientSecret).commit();
		editor.putString("redirectUri", redirectUri).commit();
	}
	
	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		/**
		 * 下面两个注释掉的代码，仅当sdk支持sso时有效，
		 */
		if (mSsoHandler != null) {
			mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
		}
//		oAuth = new OAuthV2(clientId, clientSecret, redirectUri);
		if (requestCode == 2) {
			if (resultCode == OAuthV2AuthorizeWebView.RESULT_CODE) {
				oAuth = (OAuthV2) data.getExtras()
						.getSerializable("oauth");
				String clientId = oAuth.getClientId();
				String clientSecret = oAuth.getClientSecret();
				String redirectUri = oAuth.getRedirectUri();
				if (oAuth.getStatus() == 0) {// 授权成功
					
					Toast.makeText(getApplicationContext(), "绑定成功",
							Toast.LENGTH_SHORT).show();
					txToken = oAuth.getAccessToken().toString();
					
					long date = System.currentTimeMillis() + 30 * 24 * 60 * 60 * 1000l;
					
					/**
					 * 存储token
					 */
					saveTecentAccessToken(txToken,clientId,clientSecret,redirectUri);
				}
			}
			
			
//			try {
//				tAPI.add(oAuth, "json", "我刚刚听了@qdreader,", "");
//			} catch (Exception e) {
//				// TODO: handle exception
//			} finally {
//				tAPI.shutdownConnection();
//			}
			
			
			
		}
	}
	
	
	public static void share(String conetent) {
		try {
			tAPI.add(oAuth, "json", conetent, "");
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			tAPI.shutdownConnection();
		}
	}
}
